package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.comment.response.JsonResult;
import cn.tedu._05mvcboot03.comment.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.MvcUserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.MvcArticle;
import cn.tedu._05mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


import javax.servlet.http.HttpSession;

@Validated
@Slf4j
@Api(tags = "01.用户模块")
@RestController
@RequestMapping(value = "/v1/users/")
public class MvcUserController {
    @Autowired
    private MvcUserMapper mvcUserMapper;


    @ApiOperation(value = "1.登录功能")
    @PostMapping(value = "login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO" + userLoginDTO);
        UserVO userVO = mvcUserMapper.selectByUsername(userLoginDTO.getUsername(),userLoginDTO.getPassword());
        // 判断用户名是否被占用
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //登录成功
        session.setAttribute("user",userVO);
        return JsonResult.success();
    }

    @ApiOperation(value = "2.发表文章功能")
    @PostMapping(value = "article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session) {
        log.debug("userArticleDTO" + userArticleDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        //判断用户是否登录
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);//未登录
        }
        //发表文章
        MvcArticle mvcArticle = new MvcArticle();
        BeanUtils.copyProperties(userArticleDTO,mvcArticle);
        mvcArticle.setUserId(userVO.getId());
        mvcUserMapper.insertArticle(mvcArticle);
        return JsonResult.success();
    }

    //3.查询文章功能
    @ApiOperation(value = "3.查询文章功能")
    @GetMapping(value = "selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100, message = "id值必须在1-100") @RequestParam(value ="id")Integer id) {
        log.debug("id" + id);
        ArticleVO articleVO = mvcUserMapper.selectByArticleId(id);
        return JsonResult.success(articleVO);
    }
}
